package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //获取传入的验证码
        String code = userLoginDTO.getCode();
        //通过请求微信接口查询openid
        String openid = getOpenid(code);
        //判断微信登录是否成功
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);// 如果为空 则抛个异常  登录失败
        }
        //判断数据库中是否存在用户
        User user = userMapper.getUserByOpenid(openid);
        //不存在就新增用户
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();// 给User 对象赋值
            userMapper.insert(user);
        }
        // 存在就返回用户
        return user;
    }

    /**
     * 微信接口请求,查询openId
     *
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        //请求微信服务器,验证是否可以登陆
        HashMap<String, String> hashMap = new HashMap<>();
        //构造get请求的参数
        hashMap.put("appid", weChatProperties.getAppid());
        hashMap.put("secret", weChatProperties.getSecret());
        hashMap.put("js_code", code);
        hashMap.put("grant_type", "authorization_code");

        // 发起请求获取相应
        String s = HttpClientUtil.doGet(WX_LOGIN, hashMap);// 响应JSON字符串
        //把响应的对象转换成json
        JSONObject jsonObject = JSON.parseObject(s);//将JSON字符串转换成JSON对象
        String openid = jsonObject.getString("openid");//获取JSON 对象中 haha的属性值
        return openid;
    }
}
